﻿using Chloe;
using System;
using System.Collections.Generic;
using System.Text;

namespace ChloeEx.Core
{
    public delegate DbContext CreateDbContextHanddler(string connectionstring);
    public class Setting
    {
        private static Setting instance;
        private static CreateDbContextHanddler createdbHandler;
        public static Setting Instance
        {
            get
            {
                if (instance == null)
                {
                    throw new Exception("请先初始化Setting");
                }
                return instance;
            }
            set { instance = value; }
        }
        public Setting(string connectionString, CreateDbContextHanddler newDBConextFunc)
        {
            createdbHandler = newDBConextFunc ?? throw new Exception("必须初始化newDBConextFunc");
            _connectionString = connectionString??throw new Exception("连字符串必须赋值");
            ContextCreated = db => { };
        }
        private string _connectionString;
        public string ConnectionString { get { return _connectionString; } }
        public DbContext GetDbContext()
        {
            var context= createdbHandler(_connectionString);
            ContextCreated(context);
            return context;
        }
        private Action<DbContext> ContextCreated;
        /// <summary>
        /// 设置连接字符串
        /// </summary>
        /// <param name="_ConnectionString"></param>
        public void SetConnection(string _ConnectionString)
        {
            _connectionString = _ConnectionString;
        }
        /// <summary>
        /// 打印执行的SQL语句
        /// </summary>
        /// <param name="printer"></param>
        public void PrintSQL(ICommandPrinter printer)
        {
            ContextCreated = db => { db.Session.AddInterceptor(new DbCommandInterceptor(printer)); };
        }
    }
}
